package com.ithema.config;

import com.alibaba.csp.sentinel.init.InitFunc;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.csp.sentinel.command.handler.ModifyParamFlowRulesCommandHandler;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.datasource.FileWritableDataSource;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.WritableDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import com.alibaba.csp.sentinel.transport.util.WritableDataSourceRegistry;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Description Sentinel规则持久化
 * @Author wangyu
 * @Date 2021/11/14
 */
public class FilePersistence implements InitFunc {

    @Value("${srping.application.name}")
    private String applicationName;

    @Override
    public void init() throws Exception {
        String ruleDir = System.getProperty("user.name") + "/sentinel-rules/" + applicationName;
        String flowRulePath = ruleDir + "/flow-rule.json";
        String degradeRulePath = ruleDir + "/degrade-rule.json";
        String systemRulePath = ruleDir + "/system-rule.json";
        String authorityRulePath = ruleDir + "/authority-rule.json";
        String paramFlowRulePath = ruleDir + "/param-flow-rule.json";

        this.mkdirIfNotExits(ruleDir);
        this.createFileIfNotExits(flowRulePath);
        this.createFileIfNotExits(degradeRulePath);
        this.createFileIfNotExits(systemRulePath);
        this.createFileIfNotExits(authorityRulePath);
        this.createFileIfNotExits(paramFlowRulePath);

        //流控规则
        ReadableDataSource<String, List<FlowRule>> flowRuleRds = new FileRefreshableDataSource<>(flowRulePath, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
        })
        );
        //将可读数据源注册至FlowRuleManager 这样当规则文件发生变化时，就会更新规则到内存
        FlowRuleManager.register2Property(flowRuleRds.getProperty());
        WritableDataSource<List<FlowRule>> flowRuleWds = new FileWritableDataSource<>(flowRulePath, JSON::toJSONString);
        //将可写数据源注册至transport模块的WritableDataSourceRegistry中 这样收到控制台推送的规则时，Sentinel会先更新到内存，然后将规则写入到文件中
        WritableDataSourceRegistry.registerFlowDataSource(flowRuleWds);

        //降级规则
        ReadableDataSource<String, List<DegradeRule>> degradeRuleRds = new FileRefreshableDataSource<>(degradeRulePath, source -> JSON.parseObject(source, new TypeReference<List<DegradeRule>>() {
        }));
        DegradeRuleManager.register2Property(degradeRuleRds.getProperty());
        WritableDataSource<List<DegradeRule>> degradeRuleWds = new FileWritableDataSource<>(degradeRulePath, JSON::toJSONString);
        WritableDataSourceRegistry.registerDegradeDataSource(degradeRuleWds);

        //系统规则
        ReadableDataSource<String, List<SystemRule>> systemRuleRds = new FileRefreshableDataSource<>(systemRulePath, source -> JSON.parseObject(source, new TypeReference<List<SystemRule>>() {
        }));
        SystemRuleManager.register2Property(systemRuleRds.getProperty());
        WritableDataSource<List<SystemRule>> systemRuleWds = new FileWritableDataSource<>(systemRulePath, JSON::toJSONString);
        WritableDataSourceRegistry.registerSystemDataSource(systemRuleWds);

        //授权规则
        ReadableDataSource<String, List<AuthorityRule>> authorityRuleRds = new FileRefreshableDataSource<>(authorityRulePath, source -> JSON.parseObject(source, new TypeReference<List<AuthorityRule>>() {
        }));
        AuthorityRuleManager.register2Property(authorityRuleRds.getProperty());
        WritableDataSource<List<AuthorityRule>> authorityRuleWds = new FileWritableDataSource<>(authorityRulePath, JSON::toJSONString);
        WritableDataSourceRegistry.registerAuthorityDataSource(authorityRuleWds);

        //热点参数规则
        ReadableDataSource<String, List<ParamFlowRule>> paramFlowRuleRds = new FileRefreshableDataSource<>(paramFlowRulePath, source -> JSON.parseObject(source, new TypeReference<List<ParamFlowRule>>() {
        }));
        ParamFlowRuleManager.register2Property(paramFlowRuleRds.getProperty());
        WritableDataSource<List<ParamFlowRule>> paramFlowRuleWds = new FileWritableDataSource<>(paramFlowRulePath, JSON::toJSONString);
        ModifyParamFlowRulesCommandHandler.setWritableDataSource(paramFlowRuleWds);
    }

    private void mkdirIfNotExits(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
        }
    }

    private void createFileIfNotExits(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            boolean newFile = file.createNewFile();
        }
    }
}
